package com.bite.java_chatroom.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@Component
public class OnlineUserManager {
    //存储上线用户  (ConcurrentHashMap  可以保证线程安全)
    private ConcurrentHashMap<Integer, WebSocketSession> map = new ConcurrentHashMap<>();

    public boolean online(Integer userId,WebSocketSession session){
        if(map.containsKey(userId)){
            log.info("用户["+userId+"已在线]，登录失败");
            return false;
        }
        if(session == null){
            return true;
        }
        log.info("用户["+userId+"上线]");
        map.put(userId,session);
        return true;
    }

    public void offline(Integer userId,WebSocketSession session){
        if(map.get(userId) == session) {
            map.remove(userId);
            log.info("用户[" + userId + "下线]");
        }
    }

    public WebSocketSession getSession(Integer userId){
        return map.get(userId);
    }
}




